package main;


import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Timer;

import javax.servlet.ServletContext;

import modules.ClanwarLineupReceiver;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import utils.Utils;
import web.interfaces.TankSicherheitModul;
import web.utils.Cyther;
import database.Database;



public class TankSicherheit 
{
	{
		/*
		 * LOG4J Configuration
		 */
		String deployedPropsString = tasihomepath+"Logger.properties";
		Path deployedPropsPath = Paths.get(deployedPropsString);
		File deployedProps = new File(deployedPropsString);
		try
		{
			
			Properties props = new Properties();
			
			if(deployedProps.exists())
			{
				InputStream is = Files.newInputStream(deployedPropsPath);
				props.load(is);
				is.close();
			}
			else
			{
				InputStream input = this.getClass().getResourceAsStream("Logger.properties");
				props.load(input);
				input.close();
				props.setProperty("log4j.appender.fileappender_all.File", tasihomepath+"TankSicherheitCompleteLog.log");
				props.setProperty("log4j.appender.fileappender_debug.File", tasihomepath+"TankSicherheitDebugLog.log");
				
				
				InputStream input2 = this.getClass().getResourceAsStream("Logger.properties");
				String file = Utils.convertStreamToString(input2);
				input2.close();
				
				Files.createDirectories(Paths.get(tasihomepath));
				OutputStream os = Files.newOutputStream(deployedPropsPath);
				PrintWriter pw = new PrintWriter(os);
				props.store(os,"File generated by TankSicherheit");
				pw.write(file);
				pw.close();
				os.close();
				
				
				
			}
			PropertyConfigurator.configure(props);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	public static org.apache.log4j.Logger LOGGER =null;

	public static Timer timer;
	private Database database;
	public static List<TankSicherheitModul> modulelist = new ArrayList<TankSicherheitModul>();
	public static TankSicherheit tankSicherheit;
	public static ServletContext servletContext=null;
	public static String tasihomepath=System.getProperty("user.home")+File.separator+"TankSicherheit"+File.separator;
	
	public ClanwarLineupReceiver clanwarLineupReceiver = null;
	public TankSicherheit()
	{
		LOGGER= Logger.getLogger(TankSicherheit.class);
		LOGGER.info("Starting up TankSicherheit");
		if(tankSicherheit!=null)
		{
			tankSicherheit.shutdown();
		}
		tankSicherheit=this;
		init();
	}
	
	
	
	/*
	 * called by servlet on user login
	 */
	public static int staticUserloginByNameAndPw(String wotusername, String pw)
	{
		if(TankSicherheit.tankSicherheit!=null)
		{
			return tankSicherheit.userloginByName(wotusername, Cyther.hashLoginCredentials(wotusername, pw));
		}
		return -2;
	}
	
	/*
	 * created by servlet on user registration
	 */
	public static int staticCreateUserFromForm(String wotusername,String password, int wotaccountid)
	{
		if(TankSicherheit.tankSicherheit!=null)
		{
			return tankSicherheit.createUserFromForm(wotusername,  Cyther.hashLoginCredentials(wotusername, password), wotaccountid);
		}
		return -2;
	}

	
	public static boolean isPermitted(int userid, String permission)
	{
		return true;
		//TODO
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	private int createUserFromForm(String wotusername,String password, int wotaccountid)
	{
		database.createUserFromForm(wotusername, password, wotaccountid);
		return -1;
	}
	
	private int userloginByName(String wotusername, String pw)
	{
		try
		{
			ResultSet rs = database.findUserByWoTName(wotusername);
			if(rs.next())
			{
				String storedPass = rs.getString("PASSWORD");
				if(storedPass.equals(pw))
				{
					return rs.getInt("ID");
				}
				else
				{
					LOGGER.debug("credentials invalid of user "+wotusername);
					return Database.LOGIN_FAILED_INVALID_LOGIN_CREDENTIALS;
				}
			}
			else
			{
				LOGGER.debug("Database returned empty ResultSet for user "+wotusername);
				return Database.LOGIN_FAILED_EMPTY_RESULTSET;
			}

		}
		catch(Exception e)
		{
			LOGGER.warn("exception on login: "+e);
		}
		return -1;
	}
	
	

	
	public void startModule(String name)
	{
		for(TankSicherheitModul tsm:modulelist)
		{
			if(tsm.getDisplayName().equals(name))
			{
				if(!tsm.isRunning())
				{
					System.out.println("starting "+name);
					tsm.startup();
					break;
				}
			}
		}
	}
	public void stopModule(String name)
	{
		for(TankSicherheitModul tsm:modulelist)
		{
			if(tsm.getDisplayName().equals(name))
			{
				if(!tsm.isRunning())
				{
					System.out.println("stopping "+name);
					tsm.shutdown();
					break;
				}
			}
		}
	}
	
	
	
	
	public void init()
	{
		database = new Database(false);
		modulelist.add(new WoTCWBot());
		modulelist.add(new WoTGoldCaretaker(database));
		clanwarLineupReceiver = new ClanwarLineupReceiver(database);
		timer = new Timer();
	}
	public void shutdown()
	{
		timer.cancel();
		for(TankSicherheitModul tsm: modulelist)
		{
			tsm.shutdown();
		}
		if(database!=null)
		{
			database.shutdown();
		}
	}
	
}
